package com.wuliang.blog.utils;

import com.wuliang.blog.annotation.EnableSwaggerConfig;
import com.wuliang.blog.core.basic.BaseVo;
import com.wuliang.blog.core.basic.BasicEntity;
import com.wuliang.blog.response.ReturnCode;
import lombok.extern.slf4j.Slf4j;
import org.reflections.Reflections;
import org.reflections.util.ConfigurationBuilder;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 反射工具类
 */
@Slf4j
public class ClassUtils {

    /**
     * @param returnCodeFieldName ReturnCode 字段名
     * @return {@link ReturnCode}
     */
    public static ReturnCode getReturnCodeByFieldName(String returnCodeFieldName) {
//        根据返回码名称调用返回码对象
        for (ReturnCode code : ReturnCode.values()) {
            String codeName = code.toString();
            codeName = codeName.replaceAll("_", "");
            if (returnCodeFieldName.contains(codeName)) {
                return code;
            }
        }
        return null;
    }

    /**
     * @return 获取 {@link EnableSwaggerConfig} 标注的类  的限定包名
     */
    public static List<String> getBasePackages() {

        // 反射工具包，指明本项目路径
        log.info("project package was {}", ConfigurationBuilder.build("com.wuliang.blog"));
        Reflections reflections = new Reflections(ConfigurationBuilder.build("com.wuliang.blog"));
        // 声明一个集合，用来存放包的限定名
        List<String> basePackages = new ArrayList<>();
        // 获取带 EnableSwaggerConfig 注解的类
        Set<Class<?>> classList = reflections.getTypesAnnotatedWith(EnableSwaggerConfig.class);
        for (Class classes : classList) {
            // 获取被标注类的限定包名
            basePackages.add(classes.getPackage().toString());
        }
        return basePackages;
    }

    /**
     * 根据给定对象和另一个对象的class来另一个对象的属性进行 set 操作
     */
    public static <T extends BasicEntity> T setValueToFields(Object value, Class<T> tClass) {
        try {
//        首先获取tClass对象的setter方法
            List<Method> setterMethods = setterMethods(tClass);
//        然后再将value对象转换成Map以便于获取对应的属性名称
            Map<String, Object> valueOfMap = JsonUtils.objectToMap(value);
//        在根据tClass的属性名称获取map集合中对应的Value
            T entity = tClass.newInstance();
            valueOfMap.keySet().forEach(s -> {
                System.out.println("keyName: " + s);
            });
            for (Method setterMethod : setterMethods) {
//                截取set之后的方法名作为map集合的key
                String fieldName = setterMethod.getName().substring(3);
                fieldName = fieldName.substring(0, 1).toLowerCase() + fieldName.substring(1);
                if (valueOfMap.containsKey(fieldName)) {
                    Object fieldValue = valueOfMap.get(fieldName);
//                    最后依次赋值
                    setterMethod.invoke(entity, fieldValue);
                }
            }
            return entity;
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取实体类中的Setter方法
     *
     * @param tClass 实体类
     * @return Setter方法列表
     */
    private static List<Method> setterMethods(Class<? extends BasicEntity> tClass) {
        List<Method> setterMethods = new ArrayList<>();
        for (Method method : tClass.getMethods()) {
            if (method.getName().startsWith("set")) {
                setterMethods.add(method);
            }
        }
        return setterMethods;
    }

    public static <V extends BaseVo<? extends BasicEntity>> Object invokeGetMethod(V vo) {
        String entityName = vo.getClass().getSimpleName();
        String getIdMethodName = "get" + entityName.substring(0, entityName.length() - 2) + "Id";
        try {
            Method method = vo.getClass().getDeclaredMethod(getIdMethodName);
            return method.invoke(vo);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    }
}
